package com.wx.forum.service.impl;

import com.wx.forum.common.AppResult;
import com.wx.forum.common.ResultCode;
import com.wx.forum.dao.ArticleReplyMapper;
import com.wx.forum.exception.ApplicationException;
import com.wx.forum.model.ArticleReply;
import com.wx.forum.service.IArticleReplyService;
import com.wx.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ArticleReplyServicelmpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private ArticleServicelmpl articleService;
    @Override
    @Transactional
    public void creat(ArticleReply articleReply) {
        //1.参数校验
        if(articleReply == null || articleReply.getArticleId() == null
           || articleReply.getPostUserId() == null || StringUtil.isEmpty(articleReply.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.设置默认值
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        Date date = new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        //3.调用dao，写入数据库
        int row = articleReplyMapper.insertSelective(articleReply);
        if (row <= 0) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //帖子回复数加一
        articleService.addReplyCountById(articleReply.getArticleId());
        log.info("新增成功"+"ArticleId: " + articleReply.getArticleId() + "replyId: " + articleReply.getReplyId());

    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        //1.参数校验
        if (articleId == null || articleId <= 0) {
            //打印信息
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleReplyMapper.selectByArticleId(articleId);
    }
}
